package com.hw.webflux.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.filter.OrderedWebFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.util.pattern.PathPattern;
import org.springframework.web.util.pattern.PathPatternParser;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @program: spring-webflux
 * @description:
 * @author: hewei
 * @date: 2021-11-02 18:27
 **/

@Slf4j
@Component
//@Order(0)
public class commonFilter implements OrderedWebFilter {

    @Override
    public int getOrder() {
        return 0;
    }
    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
        ServerHttpRequest request=serverWebExchange.getRequest();
        ServerHttpResponse response = serverWebExchange.getResponse();
        String AuthString="请求不合法";
        log.info("请求路径："+request.getPath().pathWithinApplication());
        PathPattern pattern=new PathPatternParser().parse("/reactive/userList");

        if (pattern.matches(request.getPath().pathWithinApplication())&&request.getHeaders().containsKey("token")){
            List<String> token=request.getHeaders().get("token");
            log.info("验证token："+token.get(0));
            if (!"hw".equals(token.get(0))){
                DataBuffer buffer = response.bufferFactory().wrap(AuthString.getBytes());
                return response.writeWith(Mono.just(buffer));
            }
        }
        return webFilterChain.filter(serverWebExchange);
    }
}